using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using System;
using System.Threading.Tasks;
using System.Windows;
using WpfClient.Application.ViewModels;
using WpfClient.Infrastructure;
using WpfClient.Logging;
using WpfClient.Views;

namespace WpfClient
{
    public class AppBootstrapper
    {
        private IHost? _host;
        private IServiceProvider? _serviceProvider;

        public async Task InitializeAsync()
        {
            // 配置日志
            Log.Logger = LoggingConfiguration.CreateLogger();

            // 创建主机
            _host = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    // 注册基础设施服务
                    services.AddInfrastructureServices();
                    
                    // 注册ViewModels
                    services.AddTransient<MainViewModel>();
                    services.AddTransient<UserManagementViewModel>();
                    services.AddTransient<SocketCommunicationViewModel>();
                    
                    // 注册Views
                    services.AddTransient<MainWindow>();
                    services.AddTransient<UserManagementWindow>();
                    services.AddTransient<SocketCommunicationWindow>();
                })
                .UseSerilog()
                .Build();

            await _host.StartAsync();
            _serviceProvider = _host.Services;
        }

        public void ShowMainWindow()
        {
            var mainWindow = _serviceProvider.GetRequiredService<MainWindow>();
            var mainViewModel = _serviceProvider.GetRequiredService<MainViewModel>();
            mainWindow.DataContext = mainViewModel;
            mainWindow.Show();
        }

        public void Shutdown()
        {
            _host?.Dispose();
            Log.CloseAndFlush();
        }

        public T GetService<T>() where T : class
        {
            return _serviceProvider?.GetRequiredService<T>() ?? throw new InvalidOperationException("Service provider not initialized");
        }
    }
}